package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        // 时间字符串  营业额字符串
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }

        List<Double> doubleList = new ArrayList<>();
        // 根据时间段统计营业额
        for (LocalDate date : localDateList) {
            // 把时间转换成带有时分秒的格式
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Double dailyAmountSum = reportMapper.amountSum(beginTime, endTime);
            // 如果当前没营业额，此时dailyAmountSum为null,将其转换为0.0
            dailyAmountSum = dailyAmountSum == null ? 0.0 : dailyAmountSum;
            doubleList.add(dailyAmountSum);
        }
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(localDateList, ","))
                .turnoverList(StringUtils.join(doubleList, ","))
                .build();
        return turnoverReportVO;
    }

    /**
     * 用户统计接口
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        // 1.日期
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }

        // 2.每日新增数
        List<Integer> daliyNewUserSumList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        int sum = 0;
        for (LocalDate date : localDateList) {
            // 把时间转换成带有时分秒的格式
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            int daliyNewUserSum = reportMapper.daliyNewUserSum(beginTime, endTime);
            sum = sum + daliyNewUserSum;
            daliyNewUserSumList.add(daliyNewUserSum);
            totalUserList.add(sum);
        }

        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(localDateList, ","))
                .newUserList(StringUtils.join(daliyNewUserSumList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();
        return userReportVO;
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        // 1.日期
        List<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }

        // 订单总数，有效订单数
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : localDateList) {
            // 把时间转换成带有时分秒的格式
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);

            // 每天订单总数
            int totalOrderCount = getOrderCount(beginTime, endTime, null);
            orderCountList.add(totalOrderCount);

            // 每天有效订单数
            int validOrderCount = getOrderCount(beginTime, endTime, 5);
            validOrderCountList.add(validOrderCount);

        }

        //计算时间区间内的订单总数量
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //计算时间区间内的有效订单数量
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();

        //计算订单完成率
        // 如果总订单数为0的时候/0会报异常
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            //计算订单完成率
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(localDateList, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .build();
        return orderReportVO;
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = reportMapper.getSalesTop10(beginTime, endTime);
        List<String> names = salesTop10.stream()
                .map(GoodsSalesDTO::getName)
                .collect(Collectors.toList());

        List<Integer> numbers = salesTop10.stream()
                .map(GoodsSalesDTO::getNumber)
                .collect(Collectors.toList());

        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(names, ","))
                .numberList(StringUtils.join(numbers, ","))
                .build();
    }

    @Override
    public void export(HttpServletResponse response) throws Exception {
        // 查询近三十天的数据
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        BusinessDataVO businessDataVO = workspaceService.getBusinessData(beginTime, endTime);

        // 通过POI写入到excel文件
        FileInputStream fileInputStream = new FileInputStream(new File("D:\\java project\\sky-take-out\\sky-server\\src\\main\\resources\\template\\运营数据报表模板.xlsx"));
        XSSFWorkbook excel = new XSSFWorkbook(fileInputStream);
        XSSFSheet sheet1 = excel.getSheet("Sheet1");
        sheet1.getRow(1).getCell(1).setCellValue(begin + "至" + end);
        sheet1.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
        sheet1.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
        sheet1.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
        sheet1.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
        sheet1.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());

        //填充明细数据
        for (int i = 0; i < 30; i++) {
            LocalDate date = begin.plusDays(i);
            //查询某一天的营业数据
            BusinessDataVO businessDataVO1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
            //获得某一行
            XSSFRow row = sheet1.getRow(7 + i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessDataVO1.getTurnover());
            row.getCell(3).setCellValue(businessDataVO1.getValidOrderCount());
            row.getCell(4).setCellValue(businessDataVO1.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDataVO1.getUnitPrice());
            row.getCell(6).setCellValue(businessDataVO1.getNewUsers());
        }

        // 3.通过输出流将excel文件下载到客户端浏览器
        ServletOutputStream outputStream = response.getOutputStream();
        excel.write(outputStream);

    }

    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end, Integer status) {
        Map map = new HashMap();
        map.put("beginTime", begin);
        map.put("endTime", end);
        map.put("status", status);
        return reportMapper.totalOrderCount(map);
    }
}
